import useIsLogged from '@/hooks/common/use-loggin'
import { APIs } from '@/sdk'
import { defs } from '@/sdk/type'
import { useUser } from '@clerk/nextjs'
import moment from 'moment'
import { useCallback } from 'react'

export function useCreateUser() {
  const isLogged = useIsLogged()

  const userInfo = useUser()

  const createUser = useCallback(async () => {
    if (isLogged && localStorage.getItem('isUserUpdate') !== '1') {
      const user = userInfo.user
      const params: defs.CreateUserDto = {
        id: user?.id,
        firstName: user?.firstName || '',
        lastName: user?.lastName || '',
        userName: user?.username || '',
        phoneNumber: user?.primaryPhoneNumber?.phoneNumber,
        imageUrl: user?.imageUrl,
        email: user?.primaryEmailAddress?.emailAddress,
        lastSignInAt:
          moment(user?.lastSignInAt?.toString()).format(
            'YYYY-MM-DD HH:mm:ss'
          ) || moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      }

      const createData = await APIs.user.create.request(params)
      if (createData?.success) {
        localStorage.setItem('isUserUpdate', '1')
      }
    }
  }, [isLogged])

  return {
    createUser
  }
}
